/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
/*
 * This copy of Woodstox XML processor is licensed under the
 * Apache (Software) License, version 2.0 ("the License").
 * See the License for details about distribution rights, and the
 * specific rights regarding derivate works.
 *
 * You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/
 *
 * A copy is also included in the downloadable source code package
 * containing Woodstox, in file "ASL2.0", under the same directory
 * as this file.
 */
package com.je.bpm.engine.impl.cmd;

import com.google.common.base.Strings;
import com.je.bpm.core.model.Activity;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.MultiInstanceLoopCharacteristics;
import com.je.bpm.core.model.config.CounterSignPassTypeEnum;
import com.je.bpm.core.model.task.KaiteCounterSignUserTask;
import com.je.bpm.engine.delegate.DelegateExecution;
import com.je.bpm.engine.impl.bpmn.behavior.MultiInstanceActivityBehavior;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.persistence.entity.TaskEntity;
import com.je.bpm.engine.impl.util.ProcessDefinitionUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 更换多人任务人员命令
 */
public class MultiTaskHandoverCmd extends AbstractCompleteTaskCmd {

    private String taskId;

    private String assignee;
    private String toAssignee;

    public MultiTaskHandoverCmd(String assignee, String toAssignee, String taskId) {
        super(taskId, null, null);
        this.taskId = taskId;
        this.assignee = assignee;
        this.toAssignee = toAssignee;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getAssignee() {
        return assignee;
    }

    public void setAssignee(String assignee) {
        this.assignee = assignee;
    }

    @Override
    protected Void execute(CommandContext commandContext, TaskEntity task) {
        //判断当前执行实例的节点是否是多实例节点
        BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(task.getProcessDefinitionId());
        Activity miActivityElement = (Activity) bpmnModel.getFlowElement(task.getTaskDefinitionKey());
        MultiInstanceLoopCharacteristics loopCharacteristics = miActivityElement.getLoopCharacteristics();
        if (loopCharacteristics == null) {
            return null;
        }
        DelegateExecution rootExecution = getMultiInstanceRootExecution(task.getExecution());

        if (miActivityElement instanceof KaiteCounterSignUserTask) {
            KaiteCounterSignUserTask kaiteCounterSignUserTask = (KaiteCounterSignUserTask) miActivityElement;
            if (kaiteCounterSignUserTask.getCounterSignConfig().getCounterSignPassType() == CounterSignPassTypeEnum.PASS_PRINCIPAL) {
                String oneBallotUserId = getStringVariable(rootExecution, MultiInstanceActivityBehavior.PASS_PRINCIPAL);
                if (!Strings.isNullOrEmpty(oneBallotUserId) && oneBallotUserId.equals(assignee)) {
                    rootExecution.setVariable(MultiInstanceActivityBehavior.PASS_PRINCIPAL, toAssignee);
                    rootExecution.setVariable(MultiInstanceActivityBehavior.PRINCIPAL_OPINION, "");
                    for (DelegateExecution execution : rootExecution.getExecutions()) {
                        ExecutionEntity executionEntity = (ExecutionEntity) execution;
                        List<TaskEntity> list = executionEntity.getTasks();
                        for (TaskEntity task1 : list) {
                            task1.setVariableLocal(MultiInstanceActivityBehavior.PASS_PRINCIPAL, toAssignee);
                        }
                    }
                }
            }
        }

        List<String> users = getListVariable(rootExecution, MultiInstanceActivityBehavior.PROCESSING_USERS_INFO);
        List<String> newList = new ArrayList<>();
        for (String user : users) {
            if (user.equals(assignee)) {
                newList.add(toAssignee);
            } else {
                newList.add(user);
            }
        }

        //获取设置变量
        rootExecution.setVariable(MultiInstanceActivityBehavior.PROCESSING_USERS_INFO, newList);
        for (DelegateExecution execution : rootExecution.getExecutions()) {
            ExecutionEntity executionEntity = (ExecutionEntity) execution;
            List<TaskEntity> list = executionEntity.getTasks();
            for (TaskEntity task1 : list) {
                task1.setVariableLocal(MultiInstanceActivityBehavior.PROCESSING_USERS_INFO, newList);
            }
        }

        return null;
    }

    protected DelegateExecution getMultiInstanceRootExecution(DelegateExecution executionEntity) {
        DelegateExecution multiInstanceRootExecution = null;
        DelegateExecution currentExecution = executionEntity;
        while (currentExecution != null && multiInstanceRootExecution == null && currentExecution.getParent() != null) {
            if (currentExecution.isMultiInstanceRoot()) {
                multiInstanceRootExecution = currentExecution;
            } else {
                currentExecution = currentExecution.getParent();
            }
        }
        return multiInstanceRootExecution;
    }

}

